package com.muy.redis.common.tree.actions;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.util.concurrency.NonUrgentExecutor;
import com.muy.redis.common.tree.MTTreeCell;
import com.muy.redis.common.tree.TreeCellEventExeContext;
import com.muy.redis.common.tree.TreeCellEventHandle;
import com.muy.redis.common.tree.TreePanelMark;
import com.muy.redis.utils.JTreeUtils;
import com.muy.redis.utils.MrRedisConnectionUtils;
import com.muy.redis.view.window.redis.MrRedisTree;
import com.muy.redis.view.window.redis.bean.MrRedisDb;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisDb;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisTopDb;
import org.apache.commons.collections4.CollectionUtils;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Author jiyanghuang
 * @Date 2022/8/7 12:45
 */
public class ReloadRedisDbAction extends AbstractMTTreeCellSelectTreeAction {

    private TreePanelMark treePanelMark;

    public ReloadRedisDbAction(TreePanelMark treePanelMark) {
        super("Refresh", "Refresh", AllIcons.Actions.Refresh, treePanelMark);
        this.treePanelMark = treePanelMark;
    }

    public ReloadRedisDbAction(TreePanelMark treePanelMark, String title, String desc) {
        super(title, desc, AllIcons.Actions.Refresh, treePanelMark);
    }

    @Override
    public void handleSelectTree(DefaultMutableTreeNode mutableTreeNode, MTTreeCell mtTreeCell) {
        MrRedisTree mrRedisTree = (MrRedisTree) treePanelMark;
        MTTreeCellMrRedisTopDb mtTreeCellMrRedisTopDb = (MTTreeCellMrRedisTopDb) mtTreeCell;
        JTreeUtils.processLoading(TreeCellEventExeContext.of(mrRedisTree.jTree(), mutableTreeNode), new TreeCellEventHandle<Void>() {

            @Override
            public void process(TreeCellEventExeContext exeContext, CompletableFuture<Void> cf) throws Exception {
                ReadAction.nonBlocking(() -> {
                    List<MrRedisDb> redisDbList = MrRedisConnectionUtils.fetchDb(mtTreeCellMrRedisTopDb.getMrRedisConnectionParam());
                    List<MTTreeCellMrRedisDb> mtTreeCellMrRedisDbs = MrRedisConnectionUtils.convert(mtTreeCellMrRedisTopDb.getProject(), redisDbList);
                    return mtTreeCellMrRedisDbs;
                }).finishOnUiThread(ModalityState.defaultModalityState(), p -> {
                    if (CollectionUtils.isNotEmpty(p)) {
                        JTreeUtils.renderRepeaterTreeSub((List) p, mutableTreeNode);
                    }
                    cf.complete(null);
                }).inSmartMode(mtTreeCellMrRedisTopDb.getProject()).submit(NonUrgentExecutor.getInstance());
            }
        });
    }
}
